<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>类型模板管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="/plugins/select2/select2.css" />
    <link rel="stylesheet" href="/plugins/select2/select2-bootstrap.css" />
    <script src="/plugins/select2/select2.min.js" type="text/javascript"></script>
	<!--bootstrap-toastr-->
	<script type="text/javascript" src="/bootstrap/toastr/toastr.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/bootstrap/toastr/toastr.css">

	<script>
		$(function () {
			getListTypeTemplate();
		})

		function getListTypeTemplate() {
			$.ajax({
				url : "/typeTemplate/getListTypeTemplate",
				dataType : "json",
				type : "post",
				data : {pageNumber : $("#pageNumber").val(),name : $("#searchTemplateName").val()},
				success : function (returnData) {

					var result = returnData.data.list;
					var table = '';
					for (var i = 0; i < result.length; i++) {

						var brand = "";
						var brandValue = JSON.parse(result[i].brandIds);
						for (let j = 0; j < brandValue.length; j++) {
							brand += brandValue[j].text + ",";
						}
						var returnBrandValue = brand.substring(0, brand.length-1);

						var spec = "";
						var specValue = JSON.parse(result[i].specIds);
						for (let j = 0; j < specValue.length; j++) {
							spec += specValue[j].text + ",";
						}
						var returnSpecValue = spec.substring(0, spec.length-1);

						var custom = "";
						var customValue = JSON.parse(result[i].customAttributeItems);
						for (let j = 0; j < customValue.length; j++) {
							custom += customValue[j].text + ",";
						}
						var returnCustomValue = custom.substring(0, custom.length-1);

						table += '<tr>'
						table += '<td><input name="box" value="'+ result[i].id +'" type="checkbox" ></td>'
						table += '<td>'+ result[i].id +'</td>'
						table += '<td>'+ result[i].name +'</td>'
						table += '<td>'+ returnBrandValue +'</td>'
						table += '<td>'+ returnSpecValue +'</td>'
						table += '<td>'+ returnCustomValue +'</td>'
						table += '<td class="text-center"> '
						table += '<button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#updateTemplateModal" onclick="toUpdateTemplate('+result[i].id+')">修改</button> '
						table += "</td>"
						table += "</tr>"
					}

					$("#listTemplate").html(table);

					$("#showCount").html(returnData.data.total)
					$("#showPage").html(returnData.data.pages)

					$("#totalPage").val(returnData.data.pages)
					$("#totalCount").val(returnData.data.total)
					$("#pageNumber").val(returnData.data.pageNumer)

					var rowPages = ""
					for (var j = 1;j <= returnData.data.pages;j++){
						rowPages += "<li>"
						rowPages += "<a href='javascript:changePageNumber("+ j +")'>"+ j +"</a>"
						rowPages += "</li>"
						$("#pages").html(rowPages)
					}
				},
				error : function () {

				}
			})
		}

		function getPage(flag) {
			var pageNumber = parseInt($("#pageNumber").val());
			var totalPage = parseInt($("#totalPage").val());

			if (flag == 1){
				if (pageNumber <= 1){
					toastr.warning("已经是第一页");
					return;
				}
				$("#pageNumber").val(1);
			}else if (flag == 2) {
				if (pageNumber <= 1){
					toastr.warning("已经是第一页");
					return;
				}
				$("#pageNumber").val(pageNumber - 1);
			}else if (flag == 3){
				if (pageNumber >= totalPage){
					toastr.warning("已经是最后一页");
					return;
				}
				$("#pageNumber").val(pageNumber + 1);
			} else if (flag == 4) {
				if (pageNumber >= totalPage){
					toastr.warning("已经是最后一页");
					return;
				}
				$("#pageNumber").val(totalPage);
			}
			getListTypeTemplate();
		}

		function changePageNumber(obj) {
			$("#pageNumber").val(obj);
			getListTypeTemplate();
		}

		function reload() {
			window.location.reload();
		}

		//删除
		function deleteBatch() {
			if (confirm("确定删除吗？")) {
				var names = $("[name=box]:checked");
				var ids = [];
				$(names).each(function (i, e) {
					ids.push(e.value)
				});
				if (ids <= 0) {
					toastr.warning("请选择要删除的规格")
					return;
				}
				$.ajax({
					url : "/typeTemplate/deleteBatch",
					dataType : "json",
					type : "post",
					data : {ids : ids},
					success : function (resultData) {
						if (resultData.code == 200) {
							toastr.success(resultData.message);
						}else {
							toastr.error(resultData.message)
						}
						setTimeout(function(){
									reload();
								},1000
						);
					},
					error : function () {
						toastr.error("系统错误")
					}
				})
			}
		}

	</script>

</head>

<body class="hold-transition skin-red sidebar-mini" >
  <!-- .box-body -->
                
                    <div class="box-header with-border">
                        <h3 class="box-title">商品类型模板管理</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#addTemplateModal" ><i class="fa fa-file-o"></i> 新建</button>
                                        <button type="button" class="btn btn-default" title="删除" onclick="deleteBatch()"><i class="fa fa-trash-o"></i> 删除</button>
                                       
                                        <button type="button" class="btn btn-default" title="刷新" onclick="window.location.reload();"><i class="fa fa-refresh"></i> 刷新</button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
							                  分类模板名称：<input type="text" id="searchTemplateName">
									<button class="btn btn-default" onclick="getListTypeTemplate()">查询</button>
                                </div>
                            </div>
                            <!--工具栏/-->

			                  <!--数据列表-->
			                  <table id="dataList" class="table table-bordered table-striped table-hover dataTable">
			                      <thead>
			                          <tr>
			                              <th class="" style="padding-right:0px">
			                                  <input id="selall" type="checkbox" class="icheckbox_square-blue">
			                              </th> 
										  <th class="sorting_asc">模板ID</th>
									      <th class="sorting">分类模板名称</th>
									      <th class="sorting">关联品牌</th>
									      <th class="sorting">关联规格</th>									     
									      <th class="sorting">扩展属性</th>													     						
					                      <th class="text-center">操作</th>
			                          </tr>
			                      </thead>
			                      <tbody id="listTemplate">

			                      </tbody>
			                  </table>
			                  <!--数据列表/-->
							<div align="center">
								<nav aria-label="Page navigation">
									<input type="hidden" id="pageNumber" name="pageNumber">
									<input type="hidden" id="totalPage">
									<div class="page_num_inf">
										<i></i> 共
										<span id="showPage"></span>页<span id="showCount"></span>条
									</div>
									<ul class="pagination">
										<li>
											<a href="javascript:getPage(1);" aria-label="Previous">
												<span aria-hidden="true">首页</span>
											</a>

											<a href="javascript:getPage(2);" aria-label="Previous">
												<span aria-hidden="true">&laquo;上一页</span>
											</a>
										</li>
									</ul>
									<ul class="pagination" id="pages">

									</ul>
									<ul class="pagination">
										<li>
											<a href="javascript:getPage(3);" aria-label="Next">
												<span aria-hidden="true">下一页&raquo;</span>
											</a>
											<a href="javascript:getPage(4);" aria-label="Previous">
												<span aria-hidden="true">尾页</span>
											</a>
										</li>
									</ul>
								</nav>
							</div>
                        </div>
                        <!-- 数据表格 /-->
                     </div>
                    <!-- /.box-body -->
<!-- 增加窗口 -->
<div class="modal fade" id="addTemplateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">商品类型模板增加</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped"  width="800px">
		      	<tr>
		      		<td>商品类型</td>
		      		<td><input  class="form-control" placeholder="商品类型" id="TemplateName">  </td>
		      	</tr>			   
		      	<tr>
		      		<td>关联品牌</td>
		      		<td>
		      			<select id="brands" name="brandIds" style="width: 100%" multiple>
							<option th:each="brand : ${brands}" th:value="${brand.id}">
								[[${brand.name}]]
							</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>关联规格</td>
		      		<td>
						<select id="specs" name="specIds" style="width: 100%" multiple>
							<option th:each="spec : ${specs}" th:value="${spec.id}">
								[[${spec.specName}]]
							</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>扩展属性</td>
		      		<td>
		      			<div class="btn-group">
                             <button type="button" class="btn btn-default" onclick="add_btn()" title="新增扩展属性"><i class="fa fa-file-o"></i> 新增扩展属性</button>
                                                                    
                        </div>
						<table class="table table-bordered table-striped"  width="800px">
							<thead>
								<tr>
								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
									<td>属性名称</td>									
									<td>操作</td>
								</tr>
							</thead>
							<tbody id="table">
								<tr id="trOne">
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" onclick="del_btn(this)" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" title="删除" onclick="del_btn(this)"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
							</tbody>
						</table>	
           
		      		</td>
		      	</tr>	
		      	      
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<button class="btn btn-success" data-dismiss="modal" onclick="insertTypeTemplate()" aria-hidden="true">添加</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>
<!-- 修改窗口 -->
<div class="modal fade" id="updateTemplateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	  <div class="modal-content">
		  <div class="modal-header">
			  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			  <h3 id="myUpdateModalLabel">修改商品类型模板</h3>
		  </div>
		  <div class="modal-body">

			  <table class="table table-bordered table-striped"  width="800px">
				  <input type="hidden" id="updateTemplateId" name="id">
				  <tr>
					  <td>商品类型</td>
					  <td><input type="text" id="updateTemplateName" name="name" class="form-control" placeholder="商品类型"></td>
				  </tr>
				  <tr>
					  <td>关联品牌</td>
					  <td>
						  <select id="updateBrandIds" name="brandIds" style="width: 100%" multiple>
							  <option th:each="brand : ${brands}" th:value="${brand.id}">
								  [[${brand.name}]]
							  </option>
						  </select>
					  </td>
				  </tr>
				  <tr>
					  <td>关联规格</td>
					  <td>
						  <select id="updateSpecIds" name="specIds" style="width: 100%" multiple>
							  <option th:each="spec : ${specs}" th:value="${spec.id}">
								  [[${spec.specName}]]
							  </option>
						  </select>
					  </td>
				  </tr>

				  <tr>
					  <td>扩展属性</td>
					  <td>
						  <div class="btn-group">
							  <button type="button" class="btn btn-default" title="新增扩展属性" onclick="add_btn1()"><i class="fa fa-file-o"></i> 新增扩展属性</button>
						  </div>
						  <table class="table table-bordered table-striped"  width="800px">
							  <thead>
							  <tr>
								  <td><input type="checkbox" class="icheckbox_square-blue"></td>
								  <td>属性名称</td>
								  <td>操作</td>
							  </tr>
							  </thead>
							  <tbody id="updateTemplateTbody">

							  </tbody>
						  </table>

					  </td>
				  </tr>

			  </table>

		  </div>
		  <div class="modal-footer">
			  <button class="btn btn-success" data-dismiss="modal" aria-hidden="true" onclick="updateTemplate()">修改</button>
			  <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		  </div>
	  </div>
  </div>
</div>
</body>
</html>
<script>

	function updateTemplate(){
		var brands = $("#updateBrandIds").select2("data");
		var brandArr = [];
		$(brands).each(function (i,e) {
			brandArr.push({id:e.id, text:e.text.trim()})
		})
		var brandIdsJsonStr = JSON.stringify(brandArr);

		var specs =  $("#updateSpecIds").select2("data");
		var specArr = [];
		$(specs).each(function (i,e) {
			specArr.push({id:e.id, text:e.text.trim()})
		})
		var specIdsJsonStr = JSON.stringify(specArr);

		//获取拓展属性数据
		var trs = $("#updateTemplateTbody").children("tr");
		var costomArr =[];
		for (var i = 0; i < trs.length; i++) {
			var tds = $(trs[i]).find("td");
			var costomValue = $(tds[1]).find("input").val();
			var costoms = {text:costomValue};
			costomArr.push(costoms);
		}
		var costomJsonStr = JSON.stringify(costomArr);

		$.ajax({
			url : "/typeTemplate/updateTemplate",
			type : "post",
			data : {id : $("#updateTemplateId").val(),name : $("#updateTemplateName").val(), specIds : specIdsJsonStr, brandIds : brandIdsJsonStr, customAttributeItems : costomJsonStr},
			dataType : "json",
			success : function (returnData) {
				if (returnData.code == 200) {
					toastr.success(returnData.message);
					setTimeout(function(){
								reload();
							},1000
					);
				} else {
					toastr.error(returnData.message);
				}
			},
			error : function (returnData) {
				alert("系统错误");
			}
		})

	}

	$(function () {
		$("#brands").select2();
		$("#specs").select2();
		$("#updateSpecIds").select2();
		$("#updateBrandIds").select2();
	})
	
	function insertTypeTemplate() {

		//获取品牌数据
		var brands = $("#brands").select2("data");
		var brandArr = [];
		$(brands).each(function (i,e) {
			brandArr.push({id:e.id, text:e.text.trim()})
		})
		var brandIdsJsonStr = JSON.stringify(brandArr);

		//获取规格数据
		var specs =  $("#specs").select2("data");
		var specArr = [];
		$(specs).each(function (i,e) {
			specArr.push({id:e.id, text:e.text.trim()})
		})
		var specIdsJsonStr = JSON.stringify(specArr);

		//获取拓展属性数据
		var trs = $("#table").children("tr");
		var costomArr =[];
		for (var i = 0; i < trs.length; i++) {
			var tds = $(trs[i]).find("td");
			var costomValue = $(tds[1]).find("input").val();
			var costoms = {text:costomValue};
			costomArr.push(costoms);
		}
		var costomJsonStr = JSON.stringify(costomArr);

		$.ajax({
			url : "/typeTemplate/insertTypeTemplate",
			type : "post",
			data : {name : $("#TemplateName").val(), specIds : specIdsJsonStr, brandIds : brandIdsJsonStr, customAttributeItems : costomJsonStr},
			dataType : "json",
			success : function (returnData) {
				if (returnData.code == 200) {
					toastr.success(returnData.message);
					setTimeout(function(){
								reload();
							},1000
					);
				} else {
					toastr.error(returnData.message);
				}
			},
			error : function (returnData) {
				alert("系统错误");
			}
		})
	}
	
	function toUpdateTemplate(id) {
		$.ajax({
			url : "/typeTemplate/toUpdateTemplate/"+id,
			type : "post",
			dataType : "json",
			success : function (returnData) {
				if (returnData.code == 200) {
					var template = returnData.data;
					$("#updateTemplateId").val(template.id);
					$("#updateTemplateName").val(template.name);

					// 获取品牌的字符串，转成json，设置select2的默认选中
					var brandIdsJson = JSON.parse(template.brandIds);
					// 将该分类对应的品牌id放入集合，传入选中方法
					var selectedBrandIds = [];
					$(brandIdsJson).each(function (i, e) {
						selectedBrandIds.push(e.id);
					});
					$("#updateBrandIds").select2("val", selectedBrandIds);

					// 获取规格的字符串，转成json，设置select2的默认选中
					var updateSpecIds = JSON.parse(template.specIds);
					// 将该分类对应的规格id放入集合，传入选中select2的方法
					var selectedSpecIds = [];
					$(updateSpecIds).each(function (i, e) {
						selectedSpecIds.push(e.id);
					});
					$("#updateSpecIds").select2("val", selectedSpecIds);

					// 拓展属性回显
					var customAttributeItemsJson = JSON.parse(template.customAttributeItems);
					var html = "";
					$(customAttributeItemsJson).each(function (i, e) {
						html += "<tr id='trTwo'>";
						html += "<td><input type='checkbox' class='icheckbox_square-blue' ></td>";
						html += "<td><input type='text' value='" + e.text + "' name='customAttributeItems' class='form-control' placeholder='属性名称' ></td>";
						html += "<td><button type='button' class='btn btn-default' title='删除' onclick='del_btn(this)'><i class='fa fa-trash-o'></i> 删除</button></td>";
						html += "</tr>";
					});
					$("#updateTemplateTbody").html(html);
				} else {
					toastr.error("回显失败");
					console.log(returnData);
				}
			},
			error : function (returnData) {
				alert("系统错误");
				console.log(returnData);
			}
		})
	}

	function add_btn(){
		var $td = $("#trOne").clone();
		$("#table").append($td);
	}

	function add_btn1(){
		var $td = $("#trTwo").clone();
		$("#updateTemplateTbody").append($td);
	}

	function del_btn(o) {
		var tr = o.parentNode.parentNode;
		var tb = tr.parentNode;
		tb.removeChild(tr);
	}
</script>